package com.stylefeng.guns.modular.huamao.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.service.*;
import com.stylefeng.guns.modular.huamao.util.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
@CrossOrigin
@Controller
@RequestMapping("/app")
public class AppCardsController extends BaseController {
    @Autowired
    private IAppUsersBankcardsService iAppUsersBankcardsService;
    @Autowired
    private IAppBanksService iAppBanksService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IAppSktAreaService iAppSktAreaService;
    @Autowired
    private IAppUsersRealnameService iAppUsersRealnameService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private IUsersBankcardsService usersBankcardsService;

    /**
     * 我的银行卡
     * @return
     */
    @RequestMapping("/cards/bank")
    @ResponseBody
    public AppResult bank(){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            if(user==null){
                 return AppResult.ERROR("您未登录",-2);
            }
            List<Map<String,Object>> mapList=iAppUsersBankcardsService.selectUsersBankAndBankByUserId(user.getUserId());
            Map<String,Object> userAccountMap=iAppUserService.selectUsersAccountByUserId(user.getUserId());
            List<Object> list = new ArrayList<>();
            for (Map<String,Object> map:mapList) {
                String accNo = map.get("accNo").toString();
                SktAreas sktAreas = iAppSktAreaService.selectAreaByProvinceId(Integer.parseInt(map.get("provinceId").toString()));
                SktAreas sktAreas1 = iAppSktAreaService.selectAreaByCityId(Integer.parseInt(map.get("cityId").toString()));
                SktAreas sktAreas2 = iAppSktAreaService.selectAreaByAreaId(Integer.parseInt(map.get("areaId").toString()));
                if (MSGUtil.isBlank(map.get("bankImge"))){
                    map.put("bankImge",null);
                }
                map.put("accAdddress",sktAreas.getAreaName()+sktAreas1.getAreaName()+sktAreas2.getAreaName());
                map.put("accNo","**** **** **** "+accNo.toString().substring(accNo.length()-4));
                list.add(map);
            }
            Map<String, Object> maps = new HashMap<>();
            Map<String, Object> accountMap = new HashMap<>();
            accountMap.put("cash",userAccountMap.get("cash").toString());
            accountMap.put("kaiyuan",userAccountMap.get("kaiyuan").toString());
            accountMap.put("trueName",userAccountMap.get("trueName"));
            maps.put("account",accountMap);
            maps.put("usersCard",list);
            return AppResult.OK("查询成功！",maps);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("查询失败",-1);
        }
    }

    /**
     * 获取银行类型列表
     * @return
     */
    @RequestMapping("/cards/bankList")
    @ResponseBody
    public AppResult bankList(){
        List<Map<String,Object>> banksList=iAppBanksService.selectAllBanks();
        return AppResult.OK("查询成功！",banksList);
    }

    /**
     * 新增银行卡
     * @param accArea
     * @param provinceId
     * @param cityId
     * @param areaId
     * @param accNo
     * @param phone
     * @param bankId
     * @return
     */
    @RequestMapping("/cards/addBank")
    @ResponseBody
    public AppResult addBank(@ModelAttribute("accArea")String accArea,@ModelAttribute("provinceId")String provinceId,@ModelAttribute("cityId")String cityId,
                             @ModelAttribute("areaId")String areaId,@ModelAttribute("accNo")String accNo,@ModelAttribute("phone")String phone,
                             @ModelAttribute("bankId")String bankId){
        try{
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            Users users = iAppUserService.selectUsersByUserId(user.getUserId());
            if (MSGUtil.isBlank(users.getTrueName())){
                return AppResult.ERROR("您还未实名！",-1);
            }
            int banksCount=iAppUsersBankcardsService.selectCountByUserId(user.getUserId());
            if (banksCount>=3){
                return AppResult.ERROR("最多只能添加三张银行卡！",-1);
            }
            if (!MSGUtil.checkBankCard(accNo)){
                return AppResult.ERROR("银行卡号输入错误！",-1);
            }
            if (phone.length()>=11){
                if (!StringUtils.checkTel(phone)){
                    return AppResult.ERROR("请填写正确的联系号码",-1);
                }
            }
            UsersRealname usersRealname = iAppUsersRealnameService.selectUsersRealNameByUserId(user.getUserId());
            //银行卡四要素验证
            JSONObject bankInfoTo4 = BankUtils.getBankInfoTo4(accNo, usersRealname.getCardID(), users.getTrueName(),phone);
            String status = bankInfoTo4.get("status").toString();
            if (!status.equals("01")) {
                return AppResult.ERROR("银行卡信息有误,请填写正确信息", -1);
            }
            //-----------------------------------------------------------------------------------------
            UsersBankcards ub = new UsersBankcards();
            ub.setUserId(user.getUserId());
            ub.setAccNo(accNo);
            ub.setDataFlag(1);
            EntityWrapper<UsersBankcards> ew = new EntityWrapper<UsersBankcards>(ub);
            UsersBankcards usersBankcards1 = usersBankcardsService.selectOne(ew);
            if(usersBankcards1 != null){
                return AppResult.ERROR("银行卡不能重复添加",-1);
            }
            UsersBankcards usersBankcards = new UsersBankcards();
            usersBankcards.setCreateTime(new Date());
            usersBankcards.setUserId(user.getUserId());
            usersBankcards.setProvinceId(Integer.parseInt(provinceId));
            usersBankcards.setCityId(Integer.parseInt(cityId));
            usersBankcards.setAreaId(Integer.parseInt(areaId));
            usersBankcards.setBankId(Integer.parseInt(bankId));//银行id
            usersBankcards.setAccArea(accArea);//详细地址
            usersBankcards.setAccNo(accNo);//卡号
            usersBankcards.setPhone(phone);
            boolean insert = iAppUsersBankcardsService.insert(usersBankcards);
            if (insert){
                return AppResult.OK("添加成功！",null);
            }
            return AppResult.ERROR("执行错误，添加失败！",-1);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("执行错误，添加失败！",-1);
        }
    }

    /**
     * 删除银行卡
     * @param bankCardId
     * @return
     */
    @RequestMapping("/cards/delBank")
    @ResponseBody
    public AppResult delBank(@ModelAttribute("bankCardId")String bankCardId){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            if (user==null){
                return AppResult.ERROR("您未登录",-2);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("userId",user.getUserId());
            map.put("bankCardId",Integer.parseInt(bankCardId));
            boolean del=iAppUsersBankcardsService.deleteByIdAndUserId(map);
            if (del){
                return AppResult.OK("删除成功！",null);
            }
            return AppResult.ERROR("执行错误，删除失败！!",-1);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("执行错误，删除失败！!",-1);
        }
    }


}
